package com.cjm.one.coupon.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cjm.one.coupon.mapper.CouponInfoMapper;
import com.cjm.one.coupon.service.CouponCalculationService;
import com.cjm.one.coupon.service.CouponRangeService;
import com.cjm.one.coupon.service.CustomerCouponService;
import com.cjm.one.model.coupon.context.CouponContext;
import com.cjm.one.model.coupon.dto.CartItemDTO;
import com.cjm.one.model.coupon.dto.OrderCalculateDTO;
import com.cjm.one.model.coupon.entity.CouponInfo;
import com.cjm.one.model.coupon.entity.CustomerCoupon;
import com.cjm.one.model.coupon.vo.GoodsDiscountVO;
import com.cjm.one.model.goods.entity.GoodsSku;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class CouponCalculationServiceImpl
        extends ServiceImpl<CouponInfoMapper, CouponInfo>
        implements CouponCalculationService {
    @Resource
    private  CouponRangeService couponRangeService;
    @Resource
    private  GoodsSkuService goodsSkuService;
    @Resource
    private  CustomerCouponService customerCouponService;

    @Override
    public List<GoodsDiscountVO> calculateOptimalDiscount(OrderCalculateDTO dto) {
        // 1. 获取商品基本信息
        List<GoodsSku> skuList = getSkuDetails(dto.getCartItems());

        // 2. 获取所有可用优惠券（包含用户未领取但可用的）
        List<CouponInfo> allCoupons = getAllAvailableCoupons(dto.getUserId(), skuList);

        // 3. 构建优惠计算上下文
        CouponContext context = buildCouponContext(skuList, allCoupons);

        // 4. 执行优惠计算策略
        return new CouponStrategy().calculate(context);
    }

    private List<GoodsSku> getSkuDetails(List<CartItemDTO> items) {
        List<Long> skuIds = items.stream()
                .map(CartItemDTO::getSkuId)
                .collect(Collectors.toList());
        return goodsSkuService.lambdaQuery()
                .in(GoodsSku::getId, skuIds)
                .list();
    }

    private List<CouponInfo> getAllAvailableCoupons(Long userId, List<GoodsSku> skuList) {
        // 获取用户已领取的可用优惠券
        List<CustomerCoupon> userCoupons = customerCouponService.lambdaQuery()
                .eq(CustomerCoupon::getCustomerId, userId)
                .eq(CustomerCoupon::getStatus, 1)
                .list();

        // 获取系统所有有效优惠券（包含用户未领取但可用的）
        List<CouponInfo> systemCoupons = this.lambdaQuery()
                .eq(CouponInfo::getStatus, 1)
                .gt(CouponInfo::getExpireTime, new Date())
                .list();

        return mergeCoupons(userCoupons, systemCoupons);
    }

    // 其他辅助方法省略...
}
